<template>
  <div>
    <!-- 搜索表单 -->
    <el-form :model="page" :inline="true" class="mb-4">
      <el-form-item label="工序编码">
        <el-input v-model="page.processCode" placeholder="请输入工序编码"></el-input>
      </el-form-item>
      <el-form-item label="工序名称">
        <el-input v-model="page.processName" placeholder="请输入工序名称"></el-input>
      </el-form-item>
      <el-form-item label="是否启用">
        <el-radio-group v-model="page.isEnabled">
          <el-radio :label="true">是</el-radio>
          <el-radio :label="false">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-button type="primary" @click="fetchData">搜索</el-button>
      <el-button @click="clearForm">清空</el-button>
    </el-form>

    <!-- 操作按钮 -->
    <el-button type="primary" @click="openAddDialog">添加</el-button>

    <!-- 数据表格 -->
    <el-table :data="tableData" style="width: 100%" stripe>
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="processCode" label="工序编码" width="180">
        <template #default="{ row }">
          <span style="color: #409eff; cursor: pointer">{{ row.processCode }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="processName" label="工序名称" width="180"></el-table-column>
      <el-table-column prop="isEnabled" label="是否启用" width="120">
        <template #default="{ row }">
          <el-tag v-if="row.isEnabled">是</el-tag>
          <el-tag type="danger" v-else>否</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="remarks" label="备注" width="180"></el-table-column>
      <el-table-column fixed="right" label="操作" min-width="120">
        <template #default="scope">
          <el-link type="primary" size="small" @click="openEditDialog(scope.row)">修改</el-link>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加对话框 -->
    <el-dialog v-model="addDialogVisible" title="添加工序设置">
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="120px">
        <el-form-item label="工序编码" prop="processCode">
          <div style="display: flex; align-items: center; gap: 10px;">
            <el-input v-model="addForm.processCode" placeholder="请输入工序编码"></el-input>
            <el-switch v-model="addForm.autoGenerate" size="small" @change="handleAutoGenerate" label="自动生成"></el-switch>
          </div>
        </el-form-item>
        <el-form-item label="工序名称" prop="processName">
          <el-input v-model="addForm.processName" placeholder="请输入工序名称"></el-input>
        </el-form-item>
        <el-form-item label="外键" prop="operationStepInfoId" style="display: none;">
          <el-input v-model="addForm.operationStepInfoId" placeholder="请输入外键"></el-input>
        </el-form-item>
        <el-form-item label="是否启用" prop="isEnabled">
          <el-radio-group v-model="addForm.isEnabled">
            <el-radio :label="true">是</el-radio>
            <el-radio :label="false">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="工序说明" prop="processDescription">
          <el-input v-model="addForm.processDescription" placeholder="请输入工序说明" type="textarea" rows="2"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="addForm.remarks" placeholder="请输入备注" type="textarea" rows="2"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAddForm">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 修改对话框 -->
    <el-dialog v-model="editDialogVisible" title="修改工序">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="120px">
        <el-form-item label="工序 ID" prop="processInfoId">
          <el-input v-model="editForm.processInfoId" disabled></el-input>
        </el-form-item>
        <el-form-item label="工序编码" prop="processCode">
          <el-input v-model="editForm.processCode" placeholder="请输入工序编码"></el-input>
        </el-form-item>
        <el-form-item label="工序名称" prop="processName">
          <el-input v-model="editForm.processName" placeholder="请输入工序名称"></el-input>
        </el-form-item>
        <el-form-item label="外键" prop="operationStepInfoId" style="display: none;">
          <el-input v-model="editForm.operationStepInfoId" placeholder="请输入外键"></el-input>
        </el-form-item>
        <el-form-item label="是否启用" prop="isEnabled">
          <el-radio-group v-model="editForm.isEnabled">
            <el-radio :label="true">是</el-radio>
            <el-radio :label="false">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="editForm.remarks" placeholder="请输入备注" type="textarea" rows="2"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEditForm">提交</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 分页组件 -->
    <el-pagination
      v-model:current-page="page.index"
      v-model:page-size="page.size"
      :page-sizes="[1, 5, 10, 15]"
      :total="page.totalCount"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      class="mt-4"
    ></el-pagination>
  </div>
</template>

<script lang="ts" setup>
import axios from 'axios';
import { ElMessage, ElForm } from 'element-plus';
import { onMounted, reactive, ref } from 'vue';
const apiUrl = import.meta.env.VITE_APP_API_URL;
// 分页数据
const page = reactive({
  index: 1,
  size: 15,
  totalCount: 0,
  processCode: '',
  processName: '',
  isEnabled: true
});

// 表格数据
const tableData = ref([]);

// 添加对话框相关
const addDialogVisible = ref(false);
const addForm = reactive({
  processInfoId: 0,
  processCode: '',
  processName: '',
  isEnabled: true,
  processDescription: '',
  remarks: '',
  operationStepInfoId: null,
  isDelete: true,
  autoGenerate: false
});
const addFormRef = ref<InstanceType<typeof ElForm>>();
const addFormRules = {
  processCode: [
    { required: true, message: '工序编码不能为空', trigger: 'blur' }
  ],
  processName: [
    { required: true, message: '工序名称不能为空', trigger: 'blur' }
  ]
};

// 修改对话框相关
const editDialogVisible = ref(false);
const editForm = reactive({
  processInfoId: 0,
  processCode: '',
  processName: '',
  isEnabled: true,
  processDescription: '',
  remarks: '',
  operationStepInfoId: null,
  isDelete: true
});
const editFormRef = ref<InstanceType<typeof ElForm>>();
const editFormRules = {
  processCode: [
    { required: true, message: '工序编码不能为空', trigger: 'blur' }
  ],
  processName: [
    { required: true, message: '工序名称不能为空', trigger: 'blur' }
  ]
};

// 获取数据
const fetchData = async () => {
  try {
    const response = await axios.get(apiUrl+'/T5/Setting/ProcessingoShow', {
      params: {
        index: page.index,
        size: page.size,
        processCode: page.processCode,
        processName: page.processName,
        isEnabled: page.isEnabled
      }
    });
    tableData.value = response.data.data;
    page.totalCount = response.data.totalCount;
  } catch (error: any) {
    console.error(error);
  }
};

// 清空表单
const clearForm = () => {
  page.processCode = '';
  page.processName = '';
  page.isEnabled = true;
  page.index = 1;
  fetchData();
};

// 打开添加对话框
const openAddDialog = () => {
  addDialogVisible.value = true;
  Object.assign(addForm, {
    processInfoId: 0,
    processCode: '',
    processName: '',
    isEnabled: true,
    processDescription: '',
    remarks: '',
    operationStepInfoId: null,
    isDelete: true,
    autoGenerate: false
  });
};

// 提交添加表单
const submitAddForm = async () => {
  // 自动生成时间格式编码
  if (addForm.autoGenerate) {
    const now = new Date();
    addForm.processCode = now.toISOString()
      .replace(/[-:.T]/g, '')
      .substring(0, 14); // 取年月日时分（14位）
  }

  // 五位长度验证（这里因时间格式是14位，实际需求若需固定长度可调整，当前按时间格式处理）
  if (!addForm.processCode) {
    ElMessage.error('工序编码不能为空');
    return;
  }

  // 检查必填项
  if (!addForm.processCode || !addForm.processName) {
    ElMessage.error('工序编码和工序名称为必填项');
    return;
  }

  const addData = {
    processInfoId: addForm.processInfoId,
    processCode: addForm.processCode,
    processName: addForm.processName,
    isEnabled: addForm.isEnabled,
    processDescription: addForm.processDescription,
    remarks: addForm.remarks,
    operationStepInfoId: addForm.processInfoId,
    isDelete: addForm.isDelete
  };

  axios.post(apiUrl+'/T6/setting/Processinfo', addData)
    .then(res => {
      if (res.data.code === 100) {
        ElMessage.success('添加成功');
        addDialogVisible.value = false;
        fetchData();
      } else {
        ElMessage.error('添加失败');
      }
    })
    .catch(error => {
      if (error.response && error.response.status === 400) {
        ElMessage.error('添加请求参数错误，请检查表单数据');
        console.log('错误请求数据:', addData);
      } else {
        ElMessage.error('添加请求出错，请检查网络或服务器状态');
      }
      console.error(error);
    });
};

// 打开修改对话框
const openEditDialog = (row) => {
  editDialogVisible.value = true;
  Object.assign(editForm, row);
};

// 提交修改表单
const submitEditForm = async () => {
  await editFormRef.value?.validate();
  try {
    const response = await axios.put(apiUrl+'/T6/setting/UpdateProcessinfo', editForm);
    if (response.data.code === 206) {
      ElMessage.success('修改成功');
      editDialogVisible.value = false;
      fetchData();
    } else if (response.data.code === 400 && response.data.message.includes('operationStepInfoId')) {
      ElMessage.error('外键错误：请检查外键值是否有效');
    } else {
      ElMessage.error('修改失败：' + response.data.message);
    }
  } catch (error: any) {
    if (error.response && error.response.status === 400) {
      ElMessage.error('修改请求参数错误，请检查表单数据');
    } else {
      ElMessage.error('修改请求出错，请检查网络或服务器状态');
    }
    console.error(error);
  }
};

// 自动生成工序编码
const handleAutoGenerate = () => {
  if (addForm.autoGenerate) {
    const now = new Date();
    addForm.processCode = now.toISOString().replace(/[-:.T]/g, '').substring(0, 14);
  } else {
    addForm.processCode = '';
  }
};

// 处理分页大小变化
const handleSizeChange = (newSize: number) => {
  page.size = newSize;
  page.index = 1;
  fetchData();
};

// 处理当前页码变化
const handleCurrentChange = (newPage: number) => {
  page.index = newPage;
  fetchData();
};

// 删除工序
const handleDelete = async (processInfoId: number) => {
  try {
    const response = await axios.delete(apiUrl+'/T6/setting/Processinfo/${processInfoId}');
    if (response.data.code === 200) {
      ElMessage.success('删除成功');
      fetchData();
    } else {
      ElMessage.error('删除失败：' + response.data.message);
    }
  } catch (error: any) {
    if (error.response && error.response.status === 400) {
      ElMessage.error('删除请求参数错误，请检查工序 ID');
    } else {
      ElMessage.error('删除请求出错，请检查网络或服务器状态');
    }
    console.error(error);
  }
};

onMounted(() => {
  fetchData();
});
</script>

<style scoped>
.el-table__header th {
  background-color: #f5f7fa;
  color: #606266;
}

.el-table__row--hover {
  background-color: #f5f7fa !important;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  padding: 15px;
}

.mt-4 {
  margin-top: 20px;
}
</style>
    